irc = None

# simple google lookup

import urllib2
from urllib import quote_plus
import re
import lxml.html

def init(bot):
    global irc
    irc = bot
    bot.cmd.events['PRIVMSG'].subscribe(handle_privmsg)

def handle_privmsg(sender, args):
    global irc

    target = args[2]

    argv = args[0].split(' ')

    if not argv:
        return
    
    if len(argv[0]) == 0 or argv[0].isspace():
        return

    if argv[0] == "!google":
        if len(argv) > 1:
            _, query = args[0].split(None, 1)
            query = quote_plus(query)
            my_url = "http://www.google.com/search?q=%s&btnI=" % (query)

            try:
                opener = urllib2.build_opener()
                opener.addheaders = [('User-agent', 'Mozilla/5.0')]
                page = opener.open(my_url)
                page_url = page.geturl()
                p = lxml.html.parse(page)
                title = p.find(".//title").text
                clean_title = title.encode('ascii', 'ignore')
            
                irc.privmsg(args[2], "%s - %s" % (clean_title, page_url))
            except:
                irc.privmsg(args[2], "Failed")
    pass
